package jcer.core;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.util.List;

public class TaskComplatedHandler extends BaseEventHandler {

	TaskComplatedHandler(EventDriver driver) {
		super(driver);
	}

	@Override
	public void execute(Event event) throws Exception {
		Connection conn = event.conn;
		List<Result> resultList = conn.resultList;

		// caculate the total length of results
		int bodyLen = 4;// how many result
		for (Result result : resultList) {
			bodyLen += 4 + 4 + 4 + result.data.length;// len+taskId+taskNum+data
		}
		conn.packet.bodyLen = bodyLen;

		conn.writeBuf = ByteBuffer.allocate(bodyLen + Packet.getHeaderLen());
		conn.writeBuf.position(0);
		conn.packet.packHeader(conn.writeBuf);
		conn.packet.packBody(conn.writeBuf, resultList);
		conn.writeBuf.position(0);

		// try write results
		conn.write();
		if (conn.writeBuf.remaining() == 0) {
			// write over
			conn.state = Connection.State.READ_HEADER;
			conn.readBuf.position(0);
			conn.readBuf.limit(Packet.getHeaderLen());
			conn.socket.register(conn.selector, SelectionKey.OP_READ, conn);
			return;
		}

		// update state and register write event
		conn.socket.register(conn.selector, SelectionKey.OP_WRITE, conn);
		conn.state = Connection.State.WRITE_RESULT;
	}

	@Override
	public void init() {
	}

}
